﻿// --------------------------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="NGroup">
// Copyright (c) NGroup. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------
// <history>
//     <change who="Bui Thanh Nam" date="2013.12.04">Create</change>
// </history>

namespace NGroup.VTL.Web
{
    using System.Web.Mvc;
    using System.Web.Routing;
    using NGroup.VTL.Core.Routing;
    using System;
    using System.Configuration;
    using System.Threading;
    using System.Globalization;
    using System.Web;
    using NGroup.VTL.Core.Const;

    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static readonly string Host = System.Configuration.ConfigurationManager.AppSettings["VTLBASEURL"];

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            /* Hyphenize routing from Route level, allowing hyphens in URL */

            routes.MapHyphenatedRoute(
                "HyphenizedAdmin", // Route name
                "vuarao/{action}/{id}", // URL with parameters
                new { controller = "vuarao", action = "dang_nhap", id = UrlParameter.Optional } // Parameter defaults
            );

            routes.MapHyphenatedRoute(
                "HyphenizedAdminEditProduct", // Route name
                "vuarao/sua-san-pham/{parentIDString}/{childIDString}/{uniqueString}", // URL with parameters
                new { controller = "vuarao", action = "sua_san_pham" }, // Parameter defaults
                new { parentIDString = new NotEmpty(), childIDString = new NotEmpty(), uniqueString = new NotEmpty() }
            );

            routes.MapHyphenatedRoute(
                "HyphenizedNews", // Route name
                "tin-tuc/{action}/{id}", // URL with parameters
                new { controller = "tin-tuc", action = "danh_sach", id = UrlParameter.Optional } // Parameter defaults
            );

            routes.MapHyphenatedRoute(
                "HyphenizedRss", // Route name
                "rss/{action}/{id}", // URL with parameters
                new { controller = "rss", action = "danh_sach", id = UrlParameter.Optional } // Parameter defaults
            );

            routes.MapHyphenatedRoute(
                "HyphenizedOrder", // Route name
                "mua-hang/dat-mua", // URL with parameters
                new { controller = "mua-hang", action = "dat-mua" }
            );

            routes.MapHyphenatedRoute(
                "ChangeUICulture", // Route name
                "contentbase", // URL with parameters
                new { controller = "contentbase", action = "changelanguage" }
            );

            routes.MapHyphenatedRoute(
                "HyphenizedSingleton", // Route name
                "{controller}/{action}", // URL with parameters
                new { action = "chi_tiet" }, // Parameter defaults
                new { controller = @"^huong-dan-thanh-toan|danh-sach-khach-hang|sitemap|lien-he$" } // Constraints
            );

            routes.MapHyphenatedRoute(
                "HyphenizedProductsL0", // Route name
                "{parentUniqueString}", // URL with parameters
                new { controller = "noi_dung", action = "loai_san_pham_L0" },
                new { parentUniqueString = new NotContain(@"trang-chu|loi|Upload") } // action names to exclude
            );

            routes.MapHyphenatedRoute(
                "HyphenizedProductsL1", // Route name
                "{parentUniqueString}/{childUniqueString}", // URL with parameters
                new { controller = "noi_dung", action = "loai_san_pham_L1" },
                new { parentUniqueString = new NotContain(@"trang-chu|loi|Upload"), childUniqueString = new NotEmpty() } // action names to exclude
            );

            routes.MapHyphenatedRoute(
                "HyphenizedProductDetail", // Route name
                "{parentUniqueString}/{childUniqueString}/{productUniqueString}", // URL with parameters
                new { controller = "noi_dung", action = "chi_tiet_san_pham" },
                new { parentUniqueString = new NotContain(@"trang-chu|loi|Upload"), childUniqueString = new NotEmpty(), productUniqueString = new NotEmpty() } // action names to exclude
            );

            routes.MapHyphenatedRoute(
                "HyphenizedGlobal", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "trang_chu", action = "danh_sach", id = UrlParameter.Optional } // Parameter defaults
            );

            #region Reference Code Snippets

            /* Default routing of MVC */
            //routes.MapRoute(
            //    "Default", // Route name
            //    "{controller}/{action}/{id}", // URL with parameters
            //    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            //);            

            /* Hyphenize routing from Route level, allowing hyphens in URL */
            //routes.Add(
            //    "Hyphenated",
            //    new HyphenatedRoute(
            //        "{controller}/{action}/{id}", // URL with parameters
            //        new
            //        {
            //            controller = "Home",
            //            action = "Index",
            //            id = UrlParameter.Optional
            //        }
            //    )
            //);

            /* Hyphenize URL from RouteHandler level */
            //routes.Add(
            //    new Route(
            //        "{controller}/{action}/{id}",
            //        new RouteValueDictionary(
            //                    new
            //                    {
            //                        controller = "Home",
            //                        action = "Index",
            //                        id = UrlParameter.Optional
            //                    }),
            //        new HyphenatedRouteHandler()));

            #endregion
        }

        protected void Application_Start()
        {
            MvcHandler.DisableMvcResponseHeader = true;
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            string vtlDebug = ConfigurationManager.AppSettings["VTLDEBUG"];

            if (string.IsNullOrEmpty(vtlDebug) || vtlDebug.ToLower() != "true")
            {
                var httpContext = ((MvcApplication)sender).Context;

                httpContext.ClearError();
                httpContext.Response.Clear();

                Response.Redirect("/loi/thao-tac-khong-hop-le", false);
            }
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string protocol = HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://";

            if (!string.Join(null, new[] { protocol, Request.ServerVariables["HTTP_HOST"] }).Equals(
              Host, StringComparison.InvariantCultureIgnoreCase))
            {
                Response.RedirectPermanent(
                  (Host + HttpContext.Current.Request.RawUrl));
            }

            string language = "vi";

            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(NGroup.VTL.Core.Const.GeneralConfiguration.LanguageCookieName);

            if (cookie != null &&
                (string.Equals(cookie.Value, LanguageCodes.en.ToString(), StringComparison.OrdinalIgnoreCase) ||
                string.Equals(cookie.Value, LanguageCodes.vi.ToString(), StringComparison.OrdinalIgnoreCase)))
            {
                language = cookie.Value.ToLower();
            }

            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
        }
    }
}